/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-05-29 11:54:12
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2023-06-25 16:17:16
 * @FilePath: \greenbeeadmin\controllers\greenbee\ueditor.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package controllers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"strings"
	"time"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/google/uuid"
)

type UeditorUploadImageController struct {
	beego.Controller
}

var configJson []byte // 当客户端请求 /page/ueditor/controller?action=config 返回的json内容

func init() {
	file, err := os.Open("conf/config.json")
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	defer file.Close()
	buf := bytes.NewBuffer(nil)
	buf.ReadFrom(file)

	configJson = buf.Bytes()
}

func (c *UeditorUploadImageController) Get() {
	///action := r.URL.Query()["action"][0]
	action := c.GetString("action")
	if action == "config" {
		config(c.Ctx.ResponseWriter, c.Ctx.Request)
	}
}

func (c *UeditorUploadImageController) Post() {
	action := c.GetString("action")
	if action == "uploadimage" {
		uploadImage(c.Ctx.ResponseWriter, c.Ctx.Request)
	}
}

func config(w http.ResponseWriter, r *http.Request) {
	w.Write(configJson)
}

func uploadImage(w http.ResponseWriter, r *http.Request) {
	file, header, err := r.FormFile("upfile")
	if err != nil {
		panic(err)
	}

	//格式化为字符串,tm为Time类型
	timestamp := time.Now().Unix()
	tm := time.Unix(timestamp, 0)
	today := tm.Format("20060102")
	base_url := "static/upload/ueditor/" + today + "/"
	fileInfo, err := os.Stat(base_url)
	if os.IsNotExist(err) || fileInfo.Size() == 0 {
		//按照日期创建目录
		os.MkdirAll(base_url, os.ModePerm)
	}

	defer file.Close()
	uuids, _ := uuid.NewUUID()

	filename := strings.Replace(uuids.String(), "-", "", -1) + path.Ext(header.Filename)
	outFile, err := os.Create(path.Join("static", "upload", "ueditor", today, filename))
	if err != nil {
		panic(err)
	}

	defer outFile.Close()

	io.Copy(outFile, file)

	b, err := json.Marshal(map[string]string{
		"url":      fmt.Sprintf("/"+base_url+"%s", filename), //保存后的文件路径
		"title":    "",                                       //文件描述，对图片来说在前端会添加到title属性上
		"original": header.Filename,                          //原始文件名
		"state":    "SUCCESS",                                //上传状态，成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
	w.Write(b)
}
